import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  Query,
  UseGuards,
  ParseIntPipe,
  HttpCode,
  HttpStatus,
  Req,
} from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBearerAuth, ApiQuery } from '@nestjs/swagger';
import { PaymentService } from './payment.service';
import { CreatePaymentOrderDto, QueryPaymentOrdersDto, UpdatePaymentOrderDto, RefundOrderDto } from './dto/payment.dto';
import { JwtAuthGuard } from '@/common/guards/jwt-auth.guard';
import { PermissionGuard } from '@/common/guards/permission.guard';
import { RequirePermissions } from '@/common/decorators/permission.decorator';
import { CurrentUser } from '@/common/decorators/current-user.decorator';
import { Public } from '@/common/decorators/public.decorator';
import { Request } from 'express';

@ApiTags('支付管理')
@Controller('payment')
export class PaymentController {
  constructor(private readonly paymentService: PaymentService) {}

  @Post('orders')
  @UseGuards(JwtAuthGuard, PermissionGuard)
  @RequirePermissions('payment:create')
  @ApiBearerAuth()
  @ApiOperation({ summary: '创建支付订单' })
  async create(
    @Body() createPaymentOrderDto: CreatePaymentOrderDto,
    @CurrentUser() user: any,
    @Req() req: Request,
  ) {
    createPaymentOrderDto.clientIp = req.ip;
    return this.paymentService.create(createPaymentOrderDto, user.sub);
  }

  @Get('orders')
  @UseGuards(JwtAuthGuard, PermissionGuard)
  @RequirePermissions('payment:list')
  @ApiBearerAuth()
  @ApiOperation({ summary: '获取支付订单列表' })
  async findAll(@Query() query: QueryPaymentOrdersDto) {
    return this.paymentService.findAll(query);
  }

  @Get('orders/:id')
  @UseGuards(JwtAuthGuard, PermissionGuard)
  @RequirePermissions('payment:list')
  @ApiBearerAuth()
  @ApiOperation({ summary: '获取支付订单详情' })
  async findOne(@Param('id', ParseIntPipe) id: number) {
    return this.paymentService.findById(id);
  }

  @Patch('orders/:id')
  @UseGuards(JwtAuthGuard, PermissionGuard)
  @RequirePermissions('payment:update')
  @ApiBearerAuth()
  @ApiOperation({ summary: '更新支付订单' })
  async update(
    @Param('id', ParseIntPipe) id: number,
    @Body() updatePaymentOrderDto: UpdatePaymentOrderDto,
  ) {
    return this.paymentService.update(id, updatePaymentOrderDto);
  }

  @Delete('orders/:id')
  @UseGuards(JwtAuthGuard, PermissionGuard)
  @RequirePermissions('payment:delete')
  @ApiBearerAuth()
  @ApiOperation({ summary: '取消支付订单' })
  async cancel(@Param('id', ParseIntPipe) id: number) {
    return this.paymentService.cancelOrder(id);
  }

  @Post('orders/:id/refund')
  @UseGuards(JwtAuthGuard, PermissionGuard)
  @RequirePermissions('payment:refund')
  @ApiBearerAuth()
  @ApiOperation({ summary: '申请订单退款' })
  async refund(
    @Param('id', ParseIntPipe) id: number,
    @Body() refundOrderDto: RefundOrderDto,
  ) {
    return this.paymentService.refundOrder(id, refundOrderDto.reason);
  }

  @Public()
  @Post('callback/alipay')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: '支付宝支付回调' })
  async alipayCallback(@Body() callbackData: any) {
    await this.paymentService.handlePaymentCallback('alipay', callbackData);
    return 'success';
  }

  @Public()
  @Post('callback/wechat')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: '微信支付回调' })
  async wechatCallback(@Body() callbackData: string) {
    await this.paymentService.handlePaymentCallback('wechat', callbackData);
    return '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
  }

  @Get('stats')
  @UseGuards(JwtAuthGuard, PermissionGuard)
  @RequirePermissions('payment:stats')
  @ApiBearerAuth()
  @ApiOperation({ summary: '获取支付统计数据' })
  @ApiQuery({ name: 'startDate', required: false, description: '开始日期' })
  @ApiQuery({ name: 'endDate', required: false, description: '结束日期' })
  async getStats(
    @Query('startDate') startDate?: string,
    @Query('endDate') endDate?: string,
  ) {
    return this.paymentService.getPaymentStats(startDate, endDate);
  }
}